package com.delio.client.pagos.horarios;

import java.util.ArrayList;
import java.util.List;

import com.delio.client.idioma.DelioConstants;
import com.delio.client.idioma.DelioMessages;
import com.delio.client.util.Utilities;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SortDir;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.Record;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;

public class PanelGridHorario extends ContentPanel{

	private DelioMessages msg = GWT.create(DelioMessages.class);
	private DelioConstants k = GWT.create(DelioConstants.class);
	
	private Button btnDelete = new Button(k.eliminar(),IconHelper.createPath("images/icons/delete.gif"));
	private Button btnAdd = new Button(k.agregar(),IconHelper.createPath("images/icons/add.png"));
	private static Button btnRegistrar;
	private static Button btnCancelar;
	
	private Integer selectedSize;
	private BeanModel selectedModel;
	
	private List<BeanModel> selectedModels;
	private List<ColumnConfig> configs;
	
	private ColumnConfig column;
	private ColumnModel cm;
	
	public static EditorGrid<BeanModel> grid;
	
	public static TextField<String> txtTurno;
	public static TextField<String> txtHoraentrada;
	public static TextField<String> txtHorasalida;
	public static NumberField txtHorastrabjo;
	
	
	
	
	private CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
	private ToolBar toolBar = new ToolBar();

	

	public PanelGridHorario() {
		super();
		//setHeading(k.sistemaDelio()); comentados funciona para Dialog
		setHeaderVisible(false);
		setFrame(true);
		
		//setButtons("");
		//setSize(500,350);
	//	setModal(true);
		setLayout(new FitLayout());

		configs = new ArrayList<ColumnConfig>();

	
		column = new ColumnConfig();
		column.setId("turno");
		column.setHeader(k.turno());
		column.setWidth(100);

		txtTurno = new TextField<String>();
		txtTurno.setAllowBlank(false);
		column.setEditor(new CellEditor(txtTurno));
		configs.add(column);
		
		
		column = new ColumnConfig();
		column.setId("horaentrada");
		column.setHeader(k.horaentrada());
		column.setWidth(100);

		txtHoraentrada = new TextField<String>();
		txtHoraentrada.setAllowBlank(false);
		column.setEditor(new CellEditor(txtHoraentrada));
		configs.add(column);
		
		column = new ColumnConfig();
		column.setId("horasalida");
		column.setHeader(k.horasalida());
		column.setWidth(100);

		txtHorasalida = new TextField<String>();
		txtHorasalida.setAllowBlank(false);
		column.setEditor(new CellEditor(txtHorasalida));
		configs.add(column);
		
		column = new ColumnConfig();
		column.setId("horastrabajo");
		column.setHeader(k.horastrabajo());
		column.setWidth(100);

		txtHorastrabjo = new NumberField();
		txtHorastrabjo.setPropertyEditorType(Integer.class);
		txtHorastrabjo.setAllowBlank(false);
		column.setEditor(new CellEditor(txtHorastrabjo));
		configs.add(column);
		
		configs.add(sm.getColumn());
						
		cm = new ColumnModel(configs);

		Horarios.getList();
		grid = new EditorGrid<BeanModel>(Horarios.store, cm);
		grid.setAutoExpandColumn("turno");
		grid.setBorders(true);
		grid.setSelectionModel(sm);
		grid.addPlugin(sm);  
		grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {
			@Override
			public void handleEvent(GridEvent<BeanModel> be) {
				Horarios.loader.load();

			}
		});
		grid.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {

					@Override
					public void handleEvent(SelectionChangedEvent<BeanModel> be) {
						selectedSize = be.getSelection().size();

						if (selectedSize == 0) {
							btnDelete.setEnabled(false);
						} else if (selectedSize == 1) {
							selectedModel = be.getSelectedItem();
							btnDelete.setEnabled(true);
						} else if (selectedSize > 1) {
							selectedModels = be.getSelection();
							btnDelete.setEnabled(true);
						}

					}

				});

		txtTurno.addListener(Events.Detach, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				validar(txtTurno);
			}
		});

		
		txtHoraentrada.addListener(Events.Detach, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				validar(txtHoraentrada);
			}
		});
		
		txtHorasalida.addListener(Events.Detach, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				validar(txtHorasalida);
			}
		});
		
		txtHorastrabjo.addListener(Events.Detach, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				validar(txtHorastrabjo);
			}
		});
		
		btnCancelar = new Button(k.cancelar(),IconHelper.createPath("images/icons/cancel.png"),new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
									Horarios.store.rejectChanges();
									

					}
				});
		
		btnRegistrar = new Button(k.registrar(),IconHelper.createPath("images/icons/save_all.png"),new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
						List<Record> re = Horarios.store.getModifiedRecords();
					
						for (Record r : re) {
							Horario ho = new Horario();
						
							ho.setTurno(String.valueOf(r.get("turno")));
							ho.setHoraentrada(String.valueOf(r.get("horaentrada")));
							ho.setHorasalida(String.valueOf(r.get("horasalida")));
							Integer ht=(Integer)r.get("horastrabajo");
							ho.setHorastrabajo(ht);

							if (r.get("id") != null)
								ho.setId(r.get("id").hashCode());
							Horarios.save(ho);
						}

						Horarios.store.commitChanges();
						btnRegistrar.setEnabled(false);
					}
				});
		btnAdd.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Horario ho = new Horario();
				ho.setTurno("");
				ho.setHoraentrada("");
				ho.setHorasalida("");
				ho.setHorastrabajo(0);
		
				BeanModelFactory beanModelFactory =  BeanModelLookup.get().getFactory(ho.getClass());
				grid.stopEditing();
		
				Horarios.store.insert(beanModelFactory.createModel(ho), 0);
				grid.startEditing(Horarios.store.indexOf(beanModelFactory.createModel(ho)), 0);

			}
		});
		btnDelete.setEnabled(false);
		final Listener<MessageBoxEvent> listener = new Listener<MessageBoxEvent>() {
			@Override
			public void handleEvent(MessageBoxEvent ce) {
				String button_id = ce.getButtonClicked().getItemId();
				if (Dialog.YES == button_id) {

					if (selectedSize == 1) {
						Integer id = selectedModel.get("id");
						Horarios.delete(id);
					} else if (selectedSize > 1) {
						String ids = Utilities.toIds(selectedModels);
						Horarios.deleteAll(ids);
					}
				}
			}
		};

		SelectionListener<ButtonEvent> sl_delete;
		sl_delete = new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				String mensaje = "";
				if (selectedSize == 1) {
					String nombres = selectedModel.get("tipo");
					mensaje = msg.empleadoEstaSeguro(nombres);
				} else if (selectedSize > 1) {
					mensaje = k.eliminarAll();
				}
				MessageBox.confirm(k.confirmacion(), mensaje, listener)
						.getDialog().getButtonById(Dialog.YES)
						.setText(k.si());

			}

		};
		btnDelete.addSelectionListener(sl_delete);
	

		addButton(btnRegistrar);
		addButton(btnCancelar);

		toolBar.add(btnAdd);
		toolBar.add(btnDelete);

		setTopComponent(toolBar);

		btnRegistrar.setEnabled(false);
		setButtonAlign(HorizontalAlignment.CENTER);
		add(grid);

	}
	
	
	private void validar(TextField<String> txt){
		if (txt.getValue() == null) {
			if (Horarios.store.getSortDir().equals(SortDir.ASC)|| Horarios.store.getSortDir().equals(SortDir.NONE))
				grid.getStore().remove(grid.getStore().getAt(0));
			else if (Horarios.store.getSortDir().equals(SortDir.DESC)|| Horarios.store.getSortDir().equals(SortDir.NONE))
				grid.getStore().remove(grid.getStore().getAt(grid.getStore().getCount() - 1));

			btnRegistrar.setEnabled(false);

		} else if (txt.getValue() != null)
			btnRegistrar.setEnabled(true);
		
	}
	
	private void validar(NumberField txt){
		if (txt.getValue() == null) {
			if (Horarios.store.getSortDir().equals(SortDir.ASC)|| Horarios.store.getSortDir().equals(SortDir.NONE))
				grid.getStore().remove(grid.getStore().getAt(0));
			else if (Horarios.store.getSortDir().equals(SortDir.DESC)|| Horarios.store.getSortDir().equals(SortDir.NONE))
				grid.getStore().remove(grid.getStore().getAt(grid.getStore().getCount() - 1));

			btnRegistrar.setEnabled(false);

		} else if (txt.getValue() != null)
			btnRegistrar.setEnabled(true);
		
	}
}
